//
//  DesSearchVC.m
//  HappyTrip
//
//  Created by yuxuesong on 15-3-31.
//  Copyright (c) 2015年 lanou3g.com 蓝鸥科技. All rights reserved.
//

#import "DesSearchVC.h"
#import "SectionView.h"
#import "MBProgressHUD.h"
#import "DesSearchObj.h"
#import "DestinationDetailObject.h"
#import "DesSearchCVC.h"
#import "SectionView.h"
#import "DestinationCountryViewController.h"
#import "DesSearchDataObj.h"
#import "DestinationHomePageObject.h"
#import "DesSearchedVC.h"

#define SEARCHIdentifier @"collectionViewCellReuse"
#define HEADERREUSE @"headerSectionReuse"

@interface DesSearchVC () <UICollectionViewDataSource, UICollectionViewDelegate, UISearchBarDelegate, UICollectionViewDelegateFlowLayout>

@property (nonatomic, retain) UISearchBar *searchBar;

@property (nonatomic, retain) SectionView *sectionView;
@property (nonatomic, retain) MBProgressHUD *progressHUD;

@property (nonatomic, retain) UICollectionView *collectionView;
@property (nonatomic, retain) NSMutableArray *headerArr;
@property (nonatomic, retain) NSMutableArray *itemsArr;
@property (nonatomic, retain) NSMutableArray *section_itemsArr;

@end

@implementation DesSearchVC

- (void)dealloc
{
    [_collectionView release];
    [_searchBar release];
    [_sectionView release];
    [_progressHUD release];
    [_headerArr release];
    [_itemsArr release];
    [_section_itemsArr release]; // 解开会过度释放
    [super dealloc];
}

- (void)viewWillAppear:(BOOL)animated
{
    self.title = @"搜索";
    self.navigationController.navigationBar.barTintColor = [UIColor colorWithRed:0 / 255.0 green:170.0 / 255.0 blue:205.0 / 255.0 alpha:1.0];
    self.tabBarController.tabBar.hidden = NO;
    self.view.backgroundColor = [UIColor colorFromHexCode:@"#F5FFFA"];
    [self.navigationController.navigationBar setTitleTextAttributes:[NSDictionary dictionaryWithObjectsAndKeys:[UIColor whiteColor], NSForegroundColorAttributeName, nil]];
}

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    
    [self handleData];
    
    self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc] initWithTitle:@"返回" style:UIBarButtonItemStylePlain target:self action:@selector(leftBarButtonItemAction:)];
    self.navigationItem.leftBarButtonItem.tintColor = [UIColor whiteColor];
    
    self.searchBar = [[UISearchBar alloc] init];
     _searchBar.frame = CGRectMake(0, 10, VIEW_WIDTH - 40 * 2, (VIEW_HEIGHT) / 18);
    _searchBar.autoresizingMask = UIViewAutoresizingFlexibleWidth;
    _searchBar.barStyle = UIBarStyleBlackTranslucent;
    _searchBar.autocorrectionType = UITextAutocorrectionTypeNo;
    _searchBar.autocapitalizationType = UITextAutocapitalizationTypeNone;
//    _searchBar.layer.borderWidth = 2.0f;
//    _searchBar.layer.borderColor = [UIColor colorWithRed:250.0 / 255.0 green:240.0 / 255.0 blue:220.0 / 255.0 alpha:1.0].CGColor;
//    _searchBar.backgroundColor = [UIColor blackColor];
    _searchBar.layer.cornerRadius = 10;
    _searchBar.clipsToBounds = YES;
    _searchBar.layer.borderWidth = 1.0f;
    _searchBar.showsCancelButton = NO;
    _searchBar.layer.borderColor = [UIColor blackColor].CGColor;
    UIImage *btnImage = [[UIImage imageNamed:@"ticket_cancel_button@2x.png"] resizableImageWithCapInsets:UIEdgeInsetsMake(0, 0, 0, 0) resizingMode:UIImageResizingModeStretch];
    [_searchBar setSearchFieldBackgroundImage:btnImage forState:UIControlStateNormal];
    _searchBar.delegate = self;
    [_searchBar setPlaceholder:@"搜索目的地相关的游记"];
    [self.view addSubview:_searchBar];
    
    UIView *searchView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, VIEW_WIDTH - 40 * 2, (VIEW_HEIGHT) / 12)];
    _searchBar.layer.cornerRadius = 10;
    [searchView addSubview:_searchBar];
    
    self.navigationItem.titleView = searchView;
    [_searchBar release];
    [searchView release];
    
    UICollectionViewFlowLayout *flowLayout = [[UICollectionViewFlowLayout alloc] init];
    flowLayout.headerReferenceSize = CGSizeMake(VIEW_WIDTH, VIEW_WIDTH / 12);
    flowLayout.itemSize = CGSizeMake((VIEW_WIDTH - 50) / 3, (VIEW_HEIGHT) / 16);
    flowLayout.sectionInset = UIEdgeInsetsMake(10, 15, 10, 15);
    flowLayout.minimumInteritemSpacing = 5;
    flowLayout.minimumLineSpacing = 5;
    
    self.collectionView = [[UICollectionView alloc] initWithFrame:CGRectMake(0, 2, VIEW_WIDTH, VIEW_HEIGHT) collectionViewLayout:flowLayout];
    _collectionView.delegate = self;
    _collectionView.dataSource = self;
    _collectionView.backgroundColor = [UIColor colorFromHexCode:@"#F5FFFA"];
    [_collectionView registerClass:[DesSearchCVC class] forCellWithReuseIdentifier:SEARCHIdentifier];
    [self.view addSubview:_collectionView];
    [_collectionView release];
    
    self.sectionView = [[SectionView alloc] init];
    [_collectionView registerClass:[SectionView class] forSupplementaryViewOfKind:UICollectionElementKindSectionHeader withReuseIdentifier:HEADERREUSE];
    
    //转菊花
    self.progressHUD = [[MBProgressHUD alloc] initWithView:self.view];
    _progressHUD.labelText = @"请稍等...";
    _progressHUD.mode = MBProgressHUDModeIndeterminate;
    [self.view addSubview:_progressHUD];
    [_progressHUD release];
    [_progressHUD show:YES];
}

- (void)leftBarButtonItemAction:(UIBarButtonItem *)button
{
    [self.navigationController popToRootViewControllerAnimated:YES];
}

#pragma mark - 搜索框的代理方法,搜索输入框获得焦点
- (void)searchBarTextDidBeginEditing:(UISearchBar *)searchBar
{
//    [searchBar setShowsCancelButton:YES animated:YES];
    for (UIView *searchButtons in [searchBar subviews]) {
        if ([searchButtons isKindOfClass:[UIButton class]]) {
            UIButton *cancelButton = (UIButton *)searchButtons;
//             修改文字颜色
//            [cancelButton setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
//            [cancelButton setTitleColor:[UIColor whiteColor] forState:UIControlStateHighlighted];
            [cancelButton setTitle:@"取消"  forState:UIControlStateNormal];
////
////            // 修改按钮背景
////            
////            UIImage *btnImage = [[UIImage imageNamed:@"ticket_cancel_button@2x.png"] resizableImageWithCapInsets:UIEdgeInsetsMake(5, 2, 5, 2) resizingMode:UIImageResizingModeStretch];
////            [cancelButton setBackgroundImage:btnImage forState:UIControlStateNormal];
        }
    }
    searchBar.showsCancelButton = YES;
}

- (void)searchBarSearchButtonClicked:(UISearchBar *)searchBar
{
    [searchBar resignFirstResponder];
    [self setSearchControllerHidden:YES];
    DesSearchedVC *searchedVC = [[DesSearchedVC alloc] init];
    searchedVC.searchSendKey = searchBar.text;
    [self.navigationController pushViewController:searchedVC animated:YES];
    [searchedVC release];
}

- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
{
    [self.view endEditing:YES];
    _searchBar.showsCancelButton = NO;
}

- (void)searchBarCancelButtonClicked:(UISearchBar *)searchBar
{
    _searchBar.showsCancelButton = NO;
    [self.view endEditing:YES];
    [searchBar resignFirstResponder];
}

- (void)setSearchControllerHidden:(BOOL)hidden
{
    [UIView beginAnimations:nil context:nil];
    [UIView setAnimationDuration:0.2];
    [UIView commitAnimations];
}

#pragma  mark - collectionView 的协议方法
//------- section 个数
- (NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView
{
    return _headerArr.count;
}
//------- section 中 item 的个数
- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section
{
    DesSearchObj *searchObj = [_headerArr objectAtIndex:section];
    return searchObj.elements.count;
}
//------- 每个 item 中的数据
- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
{
    DesSearchCVC *cell = [collectionView dequeueReusableCellWithReuseIdentifier:SEARCHIdentifier forIndexPath:indexPath];
    DesSearchObj *searchObj = [self.headerArr objectAtIndex:indexPath.section];
    DesSearchDataObj *dataObj = [searchObj.elements objectAtIndex:indexPath.row];
    cell.searchDataObj = dataObj;
    return cell;
}
//------- header 大小
//-(CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout referenceSizeForHeaderInSection:(NSInteger)section
//{
//    CGSize size = {VIEW_WIDTH * 3 / 5, (VIEW_HEIGHT) / 15};
//    return size;
//}

#pragma mark - 设置每个 section 中的 header
- (UICollectionReusableView *)collectionView:(UICollectionView *)collectionView viewForSupplementaryElementOfKind:(NSString *)kind atIndexPath:(NSIndexPath *)indexPath
{
    UICollectionReusableView *reusableView = nil;
    self.sectionView = [collectionView dequeueReusableSupplementaryViewOfKind:UICollectionElementKindSectionHeader withReuseIdentifier:HEADERREUSE forIndexPath:indexPath];
    DesSearchObj *searchModel = [self.headerArr objectAtIndex:indexPath.section];
    self.sectionView.index = indexPath.section;
    self.sectionView.headerLable.text = searchModel.title;
    self.sectionView.headerLable.textColor = [UIColor whiteColor];
    reusableView = self.sectionView;
    return reusableView;
}
#pragma mark - 点击 cell 推出下一页面
- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath
{
    DesSearchObj *searchObj = [self.headerArr objectAtIndex:indexPath.section];
    DesSearchDataObj *dataObj = [searchObj.elements objectAtIndex:indexPath.row];
    DestinationCountryViewController *countryVC = [[DestinationCountryViewController alloc] init];
    countryVC.sendId = dataObj.idNumber;
    countryVC.sendType = dataObj.typeNumber;
    [self.navigationController pushViewController:countryVC animated:YES];
    [countryVC release];
}
#pragma mark - 首页搜索数据解析
- (void)handleData
{
    NSString *urlStr = @"http://api.breadtrip.com/destination/v3/?last_modified_since=0";
    // 本地保存数据
    NSString *docPath = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject];
    NSString *path = [NSString stringWithFormat:@"%@/%ld.happyTripDestination", docPath, [urlStr hash]];
    AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
    [manager GET:urlStr parameters:nil success:^(AFHTTPRequestOperation *operation, id responseObject) {
        BOOL result = [NSKeyedArchiver archiveRootObject:responseObject toFile:path];
        NSLog(@"存储成功: %d", result);
        NSMutableArray *search_dataArr = [responseObject objectForKey:@"search_data"];
        self.headerArr = [NSMutableArray array];
        for (NSMutableDictionary *search_dataDic in search_dataArr) {
            DesSearchObj *searchObj = [[DesSearchObj alloc] initWithDic:search_dataDic];
            [self.headerArr addObject:searchObj];
            self.section_itemsArr = [search_dataDic objectForKey:@"elements"];
            NSMutableArray *modelArray = [NSMutableArray array];
            for (NSMutableDictionary *dataDic in _section_itemsArr) {
                DesSearchDataObj *dataObj = [[DesSearchDataObj alloc] initWithDictionary:dataDic];
                [modelArray addObject:dataObj];
                [dataObj release];
            }
            searchObj.elements = modelArray;
            [searchObj release];
        }
        [_collectionView reloadData];
        [_progressHUD removeFromSuperview];
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        id resultID = [NSKeyedUnarchiver unarchiveObjectWithFile:path];
        static NSInteger i = 1;
        if (1 == i) {
            UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:@"提示" message:@"网络不给力,请检查网络" delegate:self cancelButtonTitle:@"确定" otherButtonTitles:nil, nil];
            [alertView show];
            [alertView release];
        }
        i++;
        NSMutableArray *search_dataArr = [resultID objectForKey:@"search_data"];
        self.headerArr = [NSMutableArray array];
        for (NSMutableDictionary *search_dataDic in search_dataArr) {
            DesSearchObj *searchObj = [[DesSearchObj alloc] initWithDic:search_dataDic];
            [self.headerArr addObject:searchObj];
            self.section_itemsArr = [search_dataDic objectForKey:@"elements"];
            NSMutableArray *modelArray = [NSMutableArray array];
            for (NSMutableDictionary *dataDic in _section_itemsArr) {
                DesSearchDataObj *dataObj = [[DesSearchDataObj alloc] initWithDictionary:dataDic];
                [modelArray addObject:dataObj];
                [dataObj release];
            }
            searchObj.elements = modelArray;
            [searchObj release];
        }
        [_collectionView reloadData];
        [_progressHUD removeFromSuperview];
    }];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
